// 该文件中的内容为新系统使用的axios请求接口

import { ClearnEmpryProp, } from "@/tools";
import axios, { AxiosInstance, AxiosResponse } from "axios";
import {
  PassCodeList,
  AuthErrorCode,
} from './config'

import { StandardResponse } from "@/api";
const envObj = import.meta.env
const axiosDefaultConfig = {
  baseURL: envObj.VITE_SERVER_API_BASE,
  timeout: parseInt(envObj.VITE_SERVER_TIMEOUT)
}



const SIMPLE_BUSINESS_SERVER: AxiosInstance = axios.create(axiosDefaultConfig)
/**
 * 发送服务器请求前,在请求头中添加token
 */
SIMPLE_BUSINESS_SERVER.interceptors.request.use(async config => {
  const { data, url, method } = config
  if (envObj.DEV) {
    console.log(method, url, data);
  }

  config.headers.token = sessionStorage.getItem(envObj.VITE_TOKEN_KEY)

  if (data instanceof FormData) { return config }
  // 以下为解决公钥初始化问题方案
  // 公钥未初始化完成,且没有正在请求公钥
  const clearnData = ClearnEmpryProp(data || {})
  if (envObj.VITE_ENABLE_API_APPEND_TIMESTAMP === 'ENABLE') {
    Object.assign(clearnData, { t: Date.now() })
  }
  config.data = clearnData
  return config
}, error => {
  return Promise.reject(error)
})

SIMPLE_BUSINESS_SERVER.interceptors.response.use(async (response: AxiosResponse<StandardResponse<any>>) => {
  const { code, message, data } = response.data
  // 二进制文件直接返回
  if (response.request.responseType === 'blob') {
    return response
  }
  // 出现一下代码需要重新登录
  if (AuthErrorCode.includes(code)) {
    sessionStorage.clear()
    window.location.href = `${location.protocol}//${location.host}${envObj.BASE_URL}login`
    return Promise.reject(response)
  }
  // 出现异常
  if (!PassCodeList.includes(code)) return Promise.reject(message)

  if (envObj.DEV) {
    console.log(response.config.method, response.config.url, data);
  }
  return response

}, (error) => {
  console.error(error);
  const { response } = error
  const { data, status } = response || {}
  if ((status || '').toString().startsWith('5')) return Promise.reject(data?.message || '服务器出错了QAQ~')
  return Promise.reject(data.message || error.message)
})
export {
  SIMPLE_BUSINESS_SERVER
}

